#include "precomp.h"
#include "goalcomposite.h"

namespace Tmpl {

void GoalComposite::AddSubgoal(Goal* goal)
{
	mSubGoals.push_back(goal);
}

void GoalComposite::RemoveAllSubGoals()
{
	for (SubGoalList::iterator it = mSubGoals.begin(); it != mSubGoals.end(); ++it)
	{  
		(*it)->Terminate();
		delete *it;
	}
	mSubGoals.clear();
}
char GoalComposite::ProcessSubGoals(char threadId)
{
	//	Remove all completed and failed goals from the front of the subgoal list
	while( !mSubGoals.empty() )
	{
		Goal* goal = mSubGoals.front();
		if (goal->isComplete() || goal->hasFailed())
		{
			goal->Terminate();
			delete goal;
			mSubGoals.pop_front();
		}
		else
		{
			break;
		}
	}

	 // if any subgoals remain, process the one at the front of the list
	if (!mSubGoals.empty())
	{
		Goal* goal = mSubGoals.front();
		if (goal->isInactive()) goal->Activate();
		goal->Process(threadId);
		char status = goal->GetStatus();

		// ensure that owner does not clear this goal up
		if (status == GOALSTATUS_COMPLETED && mSubGoals.size() > 1)
		{
			return GOALSTATUS_ACTIVE;
		}

		return status;
	}

	// we have no goals in the list process this one
	return GOALSTATUS_NO_SUB_GOALS;
}
bool GoalComposite::ForwardMessageToFrontMostSubgoal(const MsgData& msg)
{
	if (!mSubGoals.empty())
	{
		return mSubGoals.front()->HandleMessage(msg);
	}
	return false;
}
void GoalComposite::Render() const
{
	for (SubGoalList::const_iterator it = mSubGoals.begin(); it != mSubGoals.end(); ++it)
	{
		(*it)->Render();
	}
}

}